<?php

namespace app\admin\service;

use bxkj_common\service\Sevrice;
use think\facade\Request;
use think\Model;

class Admin extends Sevrice
{
    protected $idName = '用户';

    public function login($username, $password)
    {
        if (validate_regex($username, 'phone')) {
            $where['phone'] = $username;
        } else {
            $where['user_name'] = $username;
        }
        if (empty($where)) return $this->setError(lang('USERNAME_MUST'));
        $user = $this->where($where)->find();
        if (empty($user)) return $this->setError(lang('WRONG_SER_NAME_OR_PASSWORD'));
        $user = $user->toArray();
        $auth = $this->verifyPassword($user, $password);
        if (!$auth) return $this->setError(lang('WRONG_SER_NAME_OR_PASSWORD') . '1');
        return $this->loginByUser($user);
    }

    public static function verifyPassword($user, $password)
    {
        $auth = sha1($password . $user['ec_salt'] . 'rCt52pF2cnnKNB3Hkp');
        return $auth == $user['password'];
    }

    public function loginByUser($user)
    {
        if (!$this->checkUser($user)) return false;
        $data['last_ip'] = Request::ip();
        $data['last_login'] = time();
        $res = $this->where(array('admin_id' => $user['admin_id']))->update($data);
        unset($user['password'], $user['ec_salt']);
        return $user;
    }

    //获取用户更新信息
    public function getUpdate(int $uid)
    {
        $user = $this->where(array('admin_id' => $uid))->find();
        if (empty($user)) return $this->setError("{$this->idName}不存在");
        if (!$this->checkUser($user)) return false;
        $user = $user->toArray();
        return $user;
    }

    private function checkUser($user)
    {
        if ($user['status'] != 1) return $this->setError(lang('ACCOUNT_HAS_BEEN_FROZEN'));
        return true;
    }
}